package cServer

import (
	"os"
	"os/signal"
	"syscall"

	assetfs "github.com/elazarl/go-bindata-assetfs"

	"gitee.com/csingo/cComponents"
	"gitee.com/csingo/cLog"
)

type ServerComponent struct{}

func (i *ServerComponent) Inject(instance any) bool {
	if container.IsView(instance) {
		return container.SaveView(instance.(*assetfs.AssetFS))
	}
	if container.Is(instance) {
		return container.Save(instance)
	}
	return false
}

func (i *ServerComponent) InjectConf(config cComponents.ConfigInterface) bool {
	var result bool
	switch config.ConfigName() {
	case ServerConfigName:
		server_config = config.(*ServerConf)
		result = true
	case RouteConfigName:
		route_config = config.(*RouteConf)
		result = true
	case ComponentsConfigName:
		components_config = config.(*ComponentsConf)
		result = true
	}
	return result
}

func (i *ServerComponent) Load() {
	// 进程常驻
	osch := make(chan os.Signal, 1)
	signal.Notify(osch, os.Interrupt, syscall.SIGTERM)
	cLog.WithContext(nil, map[string]any{
		"source": "cServer.ServerComponent.Load",
	}, []cLog.Option{
		cLog.IncludePaths{},
	}).Info("启动系统信号监听")

	for { //nolint:gosimple
		select {
		case item := <-osch:
			cLog.WithContext(nil, map[string]any{
				"source": "cServer.ServerComponent.Load",
				"signal": item,
			}, []cLog.Option{
				cLog.IncludePaths{},
			}).Fatalln("捕获系统退出信号")
		}
	}
}

func (i *ServerComponent) Listen() []*cComponents.ConfigListener {
	return []*cComponents.ConfigListener{}
}

var Component = &ServerComponent{}
